package wechat.rcv.cosuming;

import java.util.Date;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import wechat.rcv.FrontController;
import wechat.rcv.RcvToken;
import wechat.rcv.util.RequestParser;
import weixin.mp.aes.AesException;
import wechat.base.snd.util.WeChatConf;
//import wechat.send.SendNewsMsg;
@Component
public class EventClickConsuming implements IMsgConsuming {
	private final String tag_content = "Content";
	private String msg;
	private final String UNAPPROVED_LIST = "UNAPPROVED_LIST";
	private final String ARRIVAL_CHECKIN = "ARRIVAL_CHECKIN";
	private final String SHOW_NOTIFICATION = "SHOW_ME";
	private final String NOTIFICATION_LIST = "NOTIFICATION_LIST";
	private final String WORKORDER_LIST = "WORKORDER_LIST";
	final static Logger logger = Logger.getLogger(FrontController.class.getName());

	
	// <xml>
	// <ToUserName><![CDATA[toUser]]></ToUserName>
	// <FromUserName><![CDATA[FromUser]]></FromUserName>
	// <CreateTime>123456789</CreateTime>
	// <MsgType><![CDATA[event]]></MsgType>
	// <Event><![CDATA[CLICK]]></Event>
	// <EventKey><![CDATA[EVENTKEY]]></EventKey>
	// <AgentID>1</AgentID>
	// </xml>
	private boolean return_yes = true;
	public EventClickConsuming() {
	}
	public EventClickConsuming(String xmlMsg) {
		msg = xmlMsg;
	}
	@Override
	public String acceptSync() throws AesException {
		String res_str = "";
//		if (RequestParser.getElementByTag(msg, "EventKey").equals(UNAPPROVED_LIST)) {
//			res_str = "List of Unapproved requests";
//			res_str = htmlStr();
//		} else if (RequestParser.getElementByTag(msg, "EventKey").equals(ARRIVAL_CHECKIN)) {
//			logger.info("ARRIVAL_CHECKIN event happens");
//			(new Thread(new Runnable() {
//				@Override
//				public void run() {
//					// TODO Auto-wechat.rcv.generated method stub
////					SendNewsMsg.sendNews(new String[] { RequestParser.getElementByTag(msg, "FromUserName") },
////							new String[] { "" }, redirectURL(), "");
//				}
//			})).start();
//			return_yes = false;
//		} 
		if (req.getEventKey().equals(NOTIFICATION_LIST)) {
			logger.info("Show Notification List");
			return createNewsMsg(req.getFromUserName(), "Notification List", "Show my notification list", "101");
		} else if (req.getEventKey().equals(WORKORDER_LIST)) {
			logger.info("Show WorkOrder List");
			return createNewsMsg(req.getFromUserName(), "WorOrder List", "Show my WorOrder list", "100");
		}
		logger.info("ARRIVAL_CHECKIN returns");
		if (return_yes)
			return createMsg(RequestParser.getElementByTag(msg, "FromUserName"), res_str);
		return res_str;
	}

	private String createMsg(String ToUserName, String content) {
		String format = "<xml>\n" + "<ToUserName><![CDATA[%1$s]]></ToUserName>\n"
				+ "<FromUserName><![CDATA[%2$s]]></FromUserName>\n" + "<CreateTime>%3$s</CreateTime>\n"
				+ "<MsgType><![CDATA[%4$s]]></MsgType>\n" + "<Content><![CDATA[%5$s]]></Content>\n" + "</xml>";

		String createTime = Long.toString(new Date().getTime());
		return String.format(format, ToUserName, RcvToken.WECHAT_CORP_ID, createTime, "text", content);
	}

	
	private String createNewsMsg(String ToUserName, String title, String description, String state) throws AesException {
		String format = "<xml>\n" 
				+ "<ToUserName><![CDATA[%1$s]]></ToUserName>\n"
				+ "<FromUserName><![CDATA[%2$s]]></FromUserName>\n" 
				+ "<CreateTime>%3$s</CreateTime>\n"
				+ "<MsgType><![CDATA[news]]></MsgType>\n" 
				+ "<ArticleCount>1</ArticleCount>\n" 
				+ "<Articles>"
				+ "<item>"
				+ "<Title><![CDATA[%4$s]]></Title>" 
				+ "<Description><![CDATA[%5$s]]></Description>"
//				+ "<PicUrl><![CDATA[picurl]]></PicUrl>"
		        + "<Url><![CDATA[http://210.22.183.30:8090/mylist?d2387fdefg3782=%1$s&dh28rfr43gh=%6$s]]></Url>"
		        + "</item>"
				+ "</xml>";
		String createTime = Long.toString(new Date().getTime());
		String ToUserName_rypt = RcvToken.getWxcpt().encrypt(RandomStringUtils.randomAlphanumeric(16),ToUserName).replace("+", "%2B");
		ToUserName_rypt = ToUserName_rypt.replace(" ", "+");
		return String.format(format, ToUserName_rypt, RcvToken.WECHAT_CORP_ID, createTime, title, description, state);
	}

	// 企业如果需要员工在跳转到企业网页时带上员工的身份信息，需构造如下的链接：
	// //
	// https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
	// private String buildAuthConnection() {
	// try {
	// String CORPID = WeChatConf.WECHAT_CORP_ID;
	// String REDIRECT_URI =
	// java.net.URLEncoder.encode(WeChatConf.CALLBACK_SERVER_URL + "/redirect",
	// "utf-8");
	// String SCOPE = "snsapi_base";
	// String STATE = "10000";
	// return " https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
	// CORPID + "&redirect_uri="
	// + REDIRECT_URI + "&response_type=code&scope=" + SCOPE + "&state=" + STATE
	// + "#wechat_redirect";
	// } catch (UnsupportedEncodingException e) {
	// // TODO Auto-wechat.rcv.generated catch block
	// e.printStackTrace();
	// }
	// return null;
	// }

	@Override
	public String acceptAsync() {
		// TODO Auto-wechat.rcv.generated method stub
		return null;
	}

	public String htmlStr() {
		String format_str = "<a href=\""+WeChatConf.CALLBACK_SERVER_URL+"/redirect?code=1111&state=10000\">点击</a>签到";
		return format_str;
	}

	public String redirectURL() {
		String format_str = WeChatConf.CALLBACK_SERVER_URL+"/redirect?code=1111&state=10000";
		// return String.format(format, RequestParser.getElementByTag(msg,
		// "FromUserName"));
		return format_str;
	}

	private RequestObj req;

	@Override
	public void setRequestObj(RequestObj ro) {
		// TODO Auto-generated method stub
		logger.info("EventClickConsuming : setRequestObj");
		req = ro;
	}
}
